//
//  UISearchBarTestViewController.m
//  TestPrj
//
//  Created by 朱铅峰 on 2020/4/22.
//  Copyright © 2020 Xing. All rights reserved.
//

#import "UISearchBarTestViewController.h"
#import "SBTObjectCellModel.h"
#import "SearchBarTestCell1.h"
#import "SearchBarTestCell2.h"
#import "YYFPSLabel.h"

@interface UISearchBarTestViewController ()<UISearchBarDelegate>

proStrong UISearchBar *searchBar;
proStrong UIButton *cancelBtn;

proStrong NSArray *namePre;
proStrong NSArray *words;
proStrong NSMutableArray *dataSource;

@end

@implementation UISearchBarTestViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.navigationItem.titleView = self.searchBar;
    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self.tableView registerNib:[UINib nibWithNibName:@"SearchBarTestCell1" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"SearchBarTestCell1"];
    [self.tableView registerClass:[SearchBarTestCell2 class] forCellReuseIdentifier:@"SearchBarTestCell2"];
    
    YYFPSLabel *label = [[YYFPSLabel alloc] initWithFrame:CGRectMake(10, kNavBarHeight+20, 60, 20)];
    label.tag = 125521;
    [self.navigationController.view addSubview:label];
    
    [self initDataAction];
}

- (void)dealloc {
    
    UIView *view = [self.navigationController.view viewWithTag:125521];
    if (view) {
        [view removeFromSuperview];
    }
}

- (void)cancelSearchAction {
    
    self.searchBar.text = nil;
    [self.searchBar resignFirstResponder];
}

- (void)initDataAction {
    
    self.namePre = @[@"Tom",@"Joe",@"Lee",@"Lebron",@"Wade",@"Ming",@"Shoot",@"Mounse",@"egg",@"Sky",@"Water"];
    self.words = @[@"11111111",@"22222222",@"3333333啊啊3",@"44444444",@"55555555",
                       @"aaaaaaaa",@"bbbb装bbbb",@"ccd的cccccc",@"dddddddd",@"eeeeeeee",
                       @"ffffffff",@"uuuuuuuu",@"oooooo嗯嗯oo",@"l为lllllll",@"mmmmmmmm",
                       @"ssssssss",@"ffffffff",@"xxxxxxxx",@"vvvvvvvv",@"nnnnnnnn",
                       @"zzzzzzzz",@"tttttttt",@"gggggggg",@"77777777",@"88呃呃888888",
                       @"@@@@@@@@",@"########",@"rrrrrrrr",@"66666666",@"99999999",
                       @"Hi",@"Nike",@"Man",@"Shoot",@"Mounse",@"egg",@"Sky",@"Water",
                       @"Light",@"Weight",@"Heavy",@"字典",@"中国文化博大精深",@"阿娥来了我去额前而且金额万人；圈儿去额为人类前而且",@"请问二前而且哦 切咧日人3人权会让 器人AA",@"犬瘟热器里日日3人3【噢热量1人家1 ",@"3人32热量据了解；去而且二哦i秋日哦去",@"俄建立连接了老人前景无量人去额老人前而且"
    ];
    self.dataSource = [NSMutableArray array];
    for (NSString *name in self.namePre) {
        NSInteger nameCount = [Utils randomNumberFrom:10 to:20];
        for (int j=0; j<nameCount; j++) {
            NSString *nName = [NSString stringWithFormat:@"%@%d",name,j];
            NSInteger wordCount = [Utils randomNumberFrom:10 to:30];
            NSMutableString *nWord = [NSMutableString string];
            for (int k=0; k<wordCount; k++) {
                NSString *w = self.words[(int)arc4random()%self.words.count];
                [nWord appendString:w];
            }
            SBTObject *object = [SBTObject new];
            object.name = nName;
            object.desc = nWord;
            SBTObjectCellModel *cellModel = [[SBTObjectCellModel alloc] initWithObject:object];
            [self.dataSource addObject:cellModel];
        }
    }
    
    [self.tableView reloadData];
}

#pragma mark - 懒加载

/// 搜索栏
- (UISearchBar *)searchBar {
    
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.width, kNavBarWithoutStatusHeight)];
        _searchBar.placeholder = @"输入前缀";
        _searchBar.delegate = self;
        @try {
            UITextField *searchField = [_searchBar valueForKey:@"searchField"];
            if (searchField) {
                for (UIView *subView in searchField.subviews) {
                    if ([subView isKindOfClass:NSClassFromString(@"_UISearchBarSearchFieldBackgroundView")]) {
                        subView.layer.cornerRadius = 4.0f;
                        subView.layer.masksToBounds = YES;
                        subView.backgroundColor = UIColor.whiteColor;
                    }
                }
            }
        } @catch (NSException *exception) {
        }
    }
    
    return _searchBar;
}

/// 取消搜索按钮
- (UIButton *)cancelBtn {
    
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        _cancelBtn.frame = CGRectMake(0, 0, 50, kNavBarWithoutStatusHeight);
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(cancelSearchAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelBtn;
}

#pragma mark - UISearchBar delegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.cancelBtn];
    
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    
    
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    
    self.navigationItem.rightBarButtonItem = nil;
    
    return YES;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    
    self.searchBar.text = nil;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
    NSLog(@"=== searchText:%@",searchText);
}

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    if ([Utils isEmptyString:searchBar.text]) {
        return;
    }
    
    NSInteger wordCount = [Utils randomNumberFrom:10 to:30];
    NSMutableString *nWord = [NSMutableString string];
    for (int k=0; k<wordCount; k++) {
        NSString *w = self.words[(int)arc4random()%self.words.count];
        [nWord appendString:w];
    }
    SBTObject *object = [SBTObject new];
    object.name = searchBar.text;
    object.desc = nWord;
    
    SBTObjectCellModel *cellModel = [[SBTObjectCellModel alloc] initWithObject:object];
    [self.dataSource insertObject:cellModel atIndex:0];
    
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    
    [self cancelSearchAction];
}

- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar {
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self cancelSearchAction];
}

- (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar {
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SearchBarTestCell1 *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchBarTestCell1" forIndexPath:indexPath];
    
//    SearchBarTestCell2 *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchBarTestCell2" forIndexPath:indexPath];
    
    SBTObjectCellModel *model = self.dataSource[indexPath.row];
    [cell loadData:model];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    SBTObjectCellModel *model = self.dataSource[indexPath.row];
    if (model.cellHeight) {
        return model.cellHeight;
    } else {
        return UITableViewAutomaticDimension;
    }
}

@end
